﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GSLMS.Core;
using GSLMS.Entity.Enum;
using GSLMS.Entity;
using System.IO;

namespace GSLMS.WebAPP.Areas.DianDang.Controllers.Apply.ProInfo
{
    public class ProInfoController : AdminBaseController
    {
        protected override string navTabId
        {
            get { return "DianDang_Apply_ProInfo"; }
        }

        private void InitSelect()
        {
            ViewData["CustList"] = new SelectList(serviceRegInfo.GetList(new TB_APP_REGINFO() { IsPaging = false, SubAssignedIn = CurentUser.SubEmp }), "ID", "CUSTNAME");
            ViewData["Product"] = new SelectList(serviceSysProduct.GetBySysetmID(Entity.Enum.SystemEnum.SystemID.典当, -1), "ID", "ProductName");
            ViewData["Source"] = EnumHelper.ToSelectListText<ApplyEnum.RegSource>();
            ViewData["LoanType"] = EnumHelper.ToSelectList<ApplyEnum.ProLoanType>();
            ViewData["DocType"] = EnumHelper.ToSelectListText<ApplyEnum.ProDocTypeName>();
            ViewData["Repayment"] = EnumHelper.ToSelectList<ApplyEnum.ProRepayment>();
            ViewData["ProStatus"] = EnumHelper.ToSelectList<ApplyEnum.ProStatus>();

        }

        public ActionResult Index(FormCollection form)
        {
            var searchParma = new TB_APP_PROINFO();
            searchParma.STATUS = -1;
            searchParma.APPDATE = null;
            searchParma.APPDATE_END = null;
            searchParma.FLOWSTATUS = 0;
            searchParma = base.SearchPara<TB_APP_PROINFO>(form, searchParma);
            searchParma.StrSort = " id desc";
            var specailList = serviceProInfo.GetList(searchParma); //new List<TB_APP_PROINFO>() { new TB_APP_PROINFO() { ID = 1, CUSTNAME = "Test", BUSSTYPE = 3 } };//

            InitSelect();
            ViewData["RowCount"] = searchParma.RowCount;
            return View(specailList);
        }

        public ActionResult Details(int id)
        {
            var model = serviceProInfo.GetByID(id);
            return View(model);
        }

        public ActionResult Create(int? id)
        {
            var model = GetProFromRegInfo(id);
            var searchParm = new TB_APP_REGINFO()
            {
                SubAssignedIn = UniversallySearchParma.SubAssignedIn,
                Pagination = new Entity.DTO.PaginationDTO() { IsPaging = false }
            };
            InitSelect();

            return View(model);
        }
        public ActionResult CreateReturn(int? id)
        {
            return RedirectToAction("Create", new { id = id });
        }
        private TB_APP_PROINFO GetProFromRegInfo(int? id)
        {
            var regID = 0;
            var model = new TB_APP_PROINFO();
            if (id.HasValue && id > 0)
            {
                model = serviceProInfo.GetByID(id.Value);
            }
            else
            {
                if (int.TryParse(Request["regid"], out regID))
                {
                    var regInfo = serviceRegInfo.GetByID(regID);
                    if (regInfo != null)
                    {
                        model = serviceProInfo.GetByRegInfoID(regID); //Helper.ConvertObject<TB_APP_PROINFO>(regInfo);
                    }
                }

            }
            model = model ?? new TB_APP_PROINFO();
            if (!id.HasValue || id == 0)
            {
                model.APPDATE = DateTime.Now;
                model.ISSPECIAL = (int)serviceRegInfo.IsSpecialExists(regID);
                model.DOCTYPE = ApplyEnum.ProDocTypeName.身份证.ToString();
            }
            return model;
        }

        [HttpPost]
        public string Create(FormCollection form)
        {
            string result = string.Empty;
            var model = new TB_APP_PROINFO();
            TryUpdateModel(model, form);
            try
            {
                model.CANCELBY = CurentUser.UserName;

                bool isSumbit = model.ID > 0 ? serviceProInfo.Update(model) : serviceProInfo.Add(model);
                if (isSumbit)
                {
                    //result = string.Format(HelperCommon.AJAXFORMAT, 200, ResourceManager.SaveSuccess, "DianDang_Apply_ProInfo_2", "DianDang/Apply/ProInfo/CreateReturn/" + model.ID, ""); 
                    result = string.Format(HelperCommon.AJAXFORMAT, 200, ResourceManager.SaveSuccess, "", "", "closeCurrent");
                }
                else
                { result = AjaxResultFail; }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }

        public ActionResult CreateHouInfo(int? id)
        {
            var model = GetProFromRegInfo(id);
            var searchParm = new TB_APP_REGINFO()
            {
                SubAssignedIn = UniversallySearchParma.SubAssignedIn,
                Pagination = new Entity.DTO.PaginationDTO() { IsPaging = false }
            };
            ViewData["SignMan"] = new SelectList(serviceEmp.GetAllEmp(), "ID", "empname");
            ViewData["Product"] = new SelectList(serviceSysProduct.GetBySysetmID(Entity.Enum.SystemEnum.SystemID.典当, -1), "ID", "ProductName");// GetListFromDict("Product");
            ViewData["Source"] = EnumHelper.ToSelectListText<ApplyEnum.RegSource>();
            ViewData["DocType"] = EnumHelper.ToSelectListText<ApplyEnum.ProDocTypeName>();
            ViewData["Repayment"] = EnumHelper.ToSelectList<ApplyEnum.ProRepayment>();
            ViewData["HouType"] = EnumHelper.ToSelectList<ApplyEnum.ProHouType>();
            ViewData["BussType"] = EnumHelper.ToSelectList<ApplyEnum.ProBussType>();

            return View(model);
        }

        public ActionResult CreateHouInfoReturn(int? id)
        {
            return RedirectToAction("Create", new { id = id });
        }
        [HttpPost]
        public string CreateHouInfo(FormCollection form)
        {
            string result = string.Empty;
            var model = new TB_APP_PROINFO();
            TryUpdateModel(model, form);
            try
            {
                model.CANCELBY = CurentUser.UserName;
                model.ProForHouInfo.REGINFOID = model.REGINFOID;
                bool isSumbit = model.ID > 0 ? serviceProInfo.Update(model) : serviceProInfo.Add(model);

                if (isSumbit)
                {
                    // result = result = string.Format(HelperCommon.AJAXFORMAT, 200, ResourceManager.SaveSuccess, "DianDang_Apply_ProInfo_4", "DianDang/Apply/ProInfo/CreateHouInfoReturn/" + model.ID, ""); 

                    result = result = string.Format(HelperCommon.AJAXFORMAT, 200, ResourceManager.SaveSuccess, "", "", "closeCurrent");
                }
                else
                { result = AjaxResultFail; }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }

        public ActionResult IsPayed()
        {
            return View();
        }

        public ActionResult TarInfoCreate(long ID)
        {
            long proID = 0;
            long.TryParse(Request["proID"], out proID);
            long regID = 0;
            long.TryParse(Request["regID"], out regID);
            var model = new TB_APP_PROTARINFO() { TELCODE = "0755", HOUTELCODE = "0755" };


            model.ID = ID;
            model.REGINFOID = regID;
            model.PROID = proID;

            if (ID > 0)
            {
                model = serviceProTarInfo.GetByID(ID);
            }
            ViewData["Relation"] = EnumHelper.ToSelectList<ApplyEnum.ProRelation>();

            return View(model);
        }

        [HttpPost]
        public string TarInfoCreate(FormCollection form)
        {
            string result = string.Empty;
            var model = new TB_APP_PROTARINFO();

            TryUpdateModel(model, form);
            try
            {
                bool isSumbit = model.ID > 0 ? serviceProTarInfo.Update(model) : serviceProTarInfo.Add(model);
                if (isSumbit)
                { result = AjaxResultSucess; }
                else
                { result = AjaxResultFail; }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }

        public ActionResult TarInfoDetails(int id)
        {
            var model = new TB_APP_PROTARINFO();
            model = serviceProTarInfo.GetByID(id);
            return View(model);
        }

        public ActionResult TarInfoList(int? id)
        {
            var model = new List<TB_APP_PROTARINFO>();
            if (id.HasValue && id > 0)
            {
                model = serviceProTarInfo.GetAll(id.Value);
            }
            return View(model);
        }

        public string TarInfoDelete(long id)
        {
            string result = string.Empty;
            if (id > 0)
            {
                if (serviceProTarInfo.Delete(id))
                {
                    result = AjaxDeleteSucess;
                }
                else
                {
                    result = AjaxDeleteFail;
                }
            }
            else
                result = AjaxDeleteFail;

            return "{" + result + "}";
        }

        public ActionResult MetInfoCreate(int? id)
        {
            var model = new List<TB_APP_PROMETINFO>();
            model = serviceProMetInfo.GetAll(id.Value);
            return View(model);
        }

        [HttpPost]
        public string MetInfoCreate(FormCollection form)
        {
            string result = string.Empty;
            var model = new TB_APP_PROMETINFO();
            TryUpdateModel(model, form);
            try
            {
                bool isSumbit = serviceProMetInfo.AddAll(model.MetInfoList);
                if (isSumbit)
                { result = AjaxResultSucess; }
                else
                { result = AjaxResultFail; }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }


        public ActionResult ConInfoCreate(int? id)
        {
            long proID = 0;
            long.TryParse(Request["proID"], out proID);
            long regID = 0;
            long.TryParse(Request["regID"], out regID);

            var model = new TB_APP_PROCONINFO() { TELCODE = "0755", HOUTELCODE = "0755" };

            model.PROID = proID;
            model.REGINFOID = regID;

            if (id.HasValue && id > 0)
            {
                model.ID = (long)id.Value;
                model = serviceProConInfo.GetByID(id.Value);
            }
            ViewData["Relation"] = EnumHelper.ToSelectList<ApplyEnum.ProRelation>();
            return View(model);
        }

        [HttpPost]
        public string ConInfoCreate(FormCollection form)
        {
            string result = string.Empty;
            var model = new TB_APP_PROCONINFO();
            TryUpdateModel(model, form);
            try
            {
                bool isSumbit = model.ID > 0 ? serviceProConInfo.Update(model) : serviceProConInfo.Add(model);
                if (isSumbit)
                { result = AjaxResultSucess; }
                else
                { result = AjaxResultFail; }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }

        public ActionResult ConInfoList(int? id)
        {
            var model = new List<TB_APP_PROCONINFO>();
            if (id.HasValue && id > 0)
            {
                model = serviceProConInfo.GetAllByProInfoID((long)id);
            }
            return View(model);
        }

        public string ConInfoDelete(long id)
        {
            string result = string.Empty;
            if (id > 0)
            {
                if (serviceProConInfo.Delete(id))
                {
                    result = AjaxDeleteSucess;
                }
                else
                {
                    result = AjaxDeleteFail;
                }
            }
            else
                result = AjaxDeleteFail;

            return "{" + result + "}";
        }

        public ActionResult ConInfoDetails(int id)
        {
            var model = new TB_APP_PROCONINFO();
            model = serviceProConInfo.GetByID(id);
            return View(model);
        }

        public ActionResult FilesInfoCreate(int? id)
        {
            long proID = 0;
            long.TryParse(Request["proID"], out proID);
            var model = new TB_APP_PROFILESINFO();
            model.PROID = proID;
            ViewData["AnnexType"] = EnumHelper.ToSelectList<ApplyEnum.ProDocTypeName>();
            return View(model);
        }

        [HttpPost]
        public string FilesInfoCreate(FormCollection form)
        {
            string result = string.Empty;
            var model = new TB_APP_PROFILESINFO();
            TryUpdateModel(model, form);
            int fileFlag = 10;
            if (int.TryParse(Request["FILEFLAG"], out fileFlag))
            {
                model.FILEFLAG = fileFlag;
            }
            else
            {
                model.FILEFLAG = 10;
            }

            #region 上传文件
            if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
            {

                UploadFileManage uploadFile = new UploadFileManage(Request.Files[0]);
                uploadFile.ClassType = navTabId;
                uploadFile.Save();
                if (!uploadFile.Error)
                {
                    //先删除旧文件
                    if (!string.IsNullOrEmpty(model.SAVEURL))
                    {
                        uploadFile.DeleteFile(model.SAVEURL);
                    }
                    model.SAVEURL = uploadFile.FileInfo["filepath"];
                    model.FILENAME = uploadFile.FileInfo["Name"];

                }
                else
                {
                    ajaxStr = string.Format(ajaxStr, 300, uploadFile.Message, navTabId, "", "");
                    return "{" + ajaxStr + "}";
                }

            }
            #endregion

            try
            {
                bool isSumbit = serviceProFilesInfo.Add(model);
                if (isSumbit)
                { result = AjaxResultSucess; }
                else
                { result = AjaxResultFail; }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }

        public ActionResult FilesInfoList(int? id)
        {
            var model = new List<TB_APP_PROFILESINFO>();
            int fileFlag = 10;
            int.TryParse(Request["FILEFLAG"], out fileFlag);
            fileFlag = fileFlag == 0 ? 10 : fileFlag;

            if (id.HasValue && id > 0)
            {
                model = serviceProFilesInfo.GetList(new TB_APP_PROFILESINFO() { PROID = id.Value });
            }
            return View(model);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult FilesInfoDownloaded(string id)
        {
            var path = Server.MapPath(id);
            var name = Path.GetFileName(path);
            return File(path, Helper.GetMimeType(id), Url.Encode(name));
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public string FilesInfoDelete(int id)
        {
            string result = string.Empty;
            try
            {
                string path = Request["path"];
                bool isDelFile = new UploadFileManage().DeleteFile(path) == 1;
                if (isDelFile)
                {
                    bool isSumbit = serviceProFilesInfo.Delete(id);
                    if (isSumbit)
                    { result = AjaxResultSucess; }
                    else
                    { result = AjaxResultFail; }
                }
                else
                {
                    result = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", ""); ;
                }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }

        public ActionResult SumbitInfo(int id)
        {
            var model = serviceProInfo.GetSubmiShow(id) ?? new TB_APP_PROINFO();
            return View(model);
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public string SumbitInfo(FormCollection form)
        {
            string result = string.Empty;
            try
            {
                var model = new GSLMS.Entity.TB_APP_PROINFO();
                long id = 0;
                long.TryParse(Request["id"], out id);
                model.ID = id;
                model.SubmitBy = CurentUser.UserName;

                bool isSumbit = serviceProInfo.SubmitPro(model);
                if (isSumbit)
                { result = AjaxResultSucess; }
                else
                { result = AjaxResultFail; }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }

        /// <summary>
        /// 取消立项申请
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public string Cancel(int id)
        {
            string result = string.Empty;
            try
            {
                bool isSumbit = serviceProInfo.CancelPro(new TB_APP_PROINFO() { ID = id, CANCELBY = CurentUser.UserName, CANCELDATE = DateTime.Now, CANCELREASON = string.Empty });
                if (isSumbit)
                { result = string.Format(HelperCommon.AJAXFORMAT, 200, ResourceManager.SaveSuccess, navTabId, "", ""); }
                else
                { result = AjaxResultFail; }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }

        public ActionResult Progress(int id)
        {
            var model = serviceProInfo.GetByID(id);
            return View(model);
        }

        public ActionResult SoluConfirm(long id)
        {
            var model = serviceProComInfo.GetAllList(id);// new List<TB_APP_PROCOMINFO>();
            ViewData["ProID"] = id;
            ViewData["isSolu"] = serviceProComInfo.IsSolued(id);
            return View(model);
        }

        [HttpPost]
        public string SoluConfirm(FormCollection form)
        {
            string result = string.Empty;
            try
            {
                long proID = 0;
                long progID = 0;
                if (long.TryParse(Request["proid"], out proID) && long.TryParse(Request["Hid_PROGID"], out progID))
                {
                    bool isSumbit = false;
                    var model =new GSLMS.Entity.TB_APP_PROCOMINFO();
                    model.PROID = proID;
                    model.PROGID = progID;
                    model.CONFIRMBY = CurentUser.UserName;
                    model.REMARK = "";

                    isSumbit = serviceProComInfo.ConfrimSolu(model);

                    if (isSumbit)
                    { result = AjaxResultSucess; }
                    else
                    { result = AjaxResultFail; }
                }
                else
                {
                    result = AjaxResultFail;
                }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }

        public ActionResult SoluBack(int id)
        {
            //var model = serviceProInfo.GetByID(id);
            ViewData["ProID"] = id;
            return View();
        }

        [HttpPost]
        public string SoluBack(FormCollection form)
        {
            string result = string.Empty;
            try
            {
                int proID = 0;
                if (int.TryParse(Request["proid"], out proID))
                {
                    string remark = Request["BACKREMARK"];
                    bool isSumbit = false;
                    isSumbit = serviceProComInfo.BackTo(proID, CurentUser.UserName, remark);
                    if (isSumbit)
                    { result = AjaxResultSucess; }
                    else
                    { result = AjaxResultFail; }
                }
                else
                {
                    result = AjaxResultFail;
                }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }

        public ActionResult ReportInfo(int id)
        {
            ViewData["RegBussType"] = EnumHelper.ToSelectList<ApplyEnum.RegBussType>();
            var model = serviceProInfo.GetProReportInfo((long)id);
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)] 
        public string ReportInfo(FormCollection form)
        {
            string result = string.Empty;
            var model = new TB_APP_PROINFO();
            TryUpdateModel(model, form);
            try
            {
                if (model != null && model.ProReport != null)
                {
                    model.ProReport.SURVEYBY = CurentUser.UserName;
                    model.ProReport.SURVEYTIME = DateTime.Now;
                    model.ProReport.STATUS = GSLMS.Core.Helper.ToInt(Request["HidReportStatus"]);

                    //if (model.ProReport.STATUS != null)
                    //{
                    //    model.ProReport.STATUS = GSLMS.Core.Helper.ToInt(Request["HidReportStatus"]);
                    //}
                }
                


                bool isSumbit = serviceProInfo.AddProReportInfo(model);
                if (isSumbit)
                { result = AjaxResultSucess; }
                else
                { result = AjaxResultFail; }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                result = AjaxResultFail;
            }

            return "{" + result + "}";
        }

        public ActionResult Repayment(int id)
        {
            var model = serviceProInfo.GetByID(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult RepaymentList(FormCollection form)
        {
            var model = new List<TB_LOAN_RETURN>();
            int proID = 0;
            DateTime payDate = DateTime.MinValue;
            int intType = 0;
            int.TryParse(form["ID"], out proID);
            DateTime.TryParse(form["PayDate"], out payDate);
            int.TryParse(form["IntType"], out intType);
            model = serviceLoanReturn.GetList(new TB_LOAN_RETURN() { PROID = proID, PAYDATE = payDate, INTTYPE = intType }) ?? new List<TB_LOAN_RETURN>();
            return View(model);
        }

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /DianDang/Special/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
